package cn.pupil.springframework.beans.factory.support;


import cn.pupil.springframework.beans.BeansException;
import cn.pupil.springframework.beans.factory.FactoryBean;
import cn.pupil.springframework.beans.factory.config.BeanDefinition;
import cn.pupil.springframework.beans.factory.config.BeanPostProcessor;
import cn.pupil.springframework.beans.factory.config.ConfigurableBeanFactory;
import cn.pupil.springframework.core.convert.ConversionService;
import cn.pupil.springframework.util.ClassUtils;
import cn.pupil.springframework.util.StringValueResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 抽象Bean工厂，BeanDefinition注册表接口
 * @Author: pupil
 * @Date: 2024/10/08 下午 10:50
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    /**
     * BeanPostProcessors to apply in createBean
     * Bean后置处理器列表用于创建Bean
     */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();

    /**
     * ClassLoader to resolve bean class names with, if necessary
     * 必要时，使用ClassLoader解析bean类名
     */
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    /**
     * String resolvers to apply e.g. to annotation attribute values
     * 用于注释属性值等的字符串解析器
     */
    private final List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();

    /**
     * 类型转换服务
     */
    private ConversionService conversionService;

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    protected <T> T doGetBean(final String name, final Object[] args) throws BeansException {
        Object sharedInstance = getSingleton(name);
        if (sharedInstance != null) {
            // 如果是 FactoryBean，则需要调用 FactoryBean#getObject
            return (T) getObjectForBeanInstance(sharedInstance, name);
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object bean = createBean(name, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, name);
    }

    /**
     * 获取Bean实例的对象
     *
     * @param beanInstance Bean实例
     * @param beanName     bean名
     * @return
     */
    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        // 判断是否为FactoryBean类型，不是则直接返回对象
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        // 从FactoryBean对象单例缓存中获取对象
        Object object = getCachedObjectForFactoryBean(beanName);

        // 当对象为空时，从Bean实例获取对象
        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }

    /**
     * 获取 bean 的定义
     *
     * @param beanName
     * @return
     * @throws BeansException
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 实例化 bean
     *
     * @param beanName
     * @param beanDefinition
     * @return
     * @throws BeansException
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        // 先移除旧的再添加
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    @Override
    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

    /**
     * Return the list of BeanPostProcessors that will get applied
     * to beans created with this factory.
     * <p>
     * 返回Bean后置处理器列表将用于Bean工厂的Bean创建
     */
    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    @Override
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public ConversionService getConversionService() {
        return conversionService;
    }

    @Override
    public boolean containsBean(String name) {
        return containsBeanDefinition(name);
    }

    protected abstract boolean containsBeanDefinition(String beanName);

    /**
     * 获取BeanClass加载器
     *
     * @return
     */
    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }



}
